package com.viu.technology.service.sms;

import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.viu.technology.util.SmsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class SmsServiceImpl implements SmsService{

    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 对手机验证码做缓存处理,每个手机号码发送验证码的间隔时间为2分钟，每个验证码有效期为5分钟，最多存在一个有效验证码
     * @param phone
     * @return
     */
    @Override
    public SendSmsResponse sendValidateCode(String phone) {
        long expire = redisTemplate.getExpire("validate:code:phone:" + phone);
        if (expire >= 3 * 60) {
            log.info("再次发送验证码时间为" + expire);
            SendSmsResponse sendSmsResponse = new SendSmsResponse();
            sendSmsResponse.setCode("fail");
            sendSmsResponse.setMessage("再次发送验证码时间为" + expire);
            return sendSmsResponse;
        }
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
        log.info("正在发送验证码-" + code + " 至" + phone);
        SendSmsResponse response = null;
        try {
            response= smsUtil.sendSms(phone, code);
            if (null != response.getCode() && response.getCode().equals("OK")) {
                log.info("验证码发送成功");
                redisTemplate.opsForValue().set("validate:code:phone:"+phone,code , 5, TimeUnit.MINUTES );
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return response;
    }

    @Override
    public boolean checkValidateCode(String phone, String code) {
        log.info("正在校验手机号为" + phone + "发送的验证码");
        String realCode = String.valueOf(redisTemplate.opsForValue().get("validate:code:phone:" + phone));
        return realCode.equals(code)?true:false;
    }

    @Override
    public QuerySendDetailsResponse querySendDetails(String bizId) {
        QuerySendDetailsResponse response = null;
        try {
            response = smsUtil.querySendDetails(bizId);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return response;
    }
}
